package com.huatai.model.service;

import com.alibaba.fastjson.JSONObject;
import com.huatai.common.constant.KafkaConstant;
import com.huatai.model.config.CustomMinioClient;
import com.huatai.model.entity.UploadTaskEntity;
import com.huatai.model.mapper.UploadTaskMapper;
import io.minio.ListPartsResponse;
import io.minio.messages.Part;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Log4j2
public class AsyncService {
	@Autowired
	private CustomMinioClient customMinioClient;
	@Autowired
	private UploadTaskMapper mapper;
	@Autowired
	private KafkaTemplate<String, Object> kafkaTemplate;

	@Async("threadPoolExecutor")
	public void asyncComplete(UploadTaskEntity task, Long bussId){
		int completeNum = 0;
		CompletableFuture<ListPartsResponse> partsAsync;
		List<Part> partList=null;
		boolean status = true;
		try {
			while (true){
				//Thread.sleep(100);
				partsAsync = customMinioClient.listPartsAsync(task.getBucketName(),
					task.getObjectKey(), task.getChunkNumber(), task.getUploadId());
				partList = partsAsync.get().result().partList();
				completeNum = partList.size();
				if(completeNum == task.getChunkNumber()){
					break;
				}
			}
			Part[] parts = new Part[partList.size()];
			for (int i = 0; i < partList.size(); i++) {
				parts[i] = partList.get(i);
			}
			customMinioClient.completeMultipartUploadAsync(task.getBucketName(), task.getObjectKey(),
				task.getUploadId(), parts);
			task.setCompleted(true);
			mapper.updateById(task);
		}catch (Exception e){
			status=false;
			log.error("文件合并异常，异常信息：{}",e.getMessage());
		}
		JSONObject data = new JSONObject();
		data.put("bussId",bussId);
		data.put("path",task.getObjectKey());
		data.put("status",status);
		kafkaTemplate.send(KafkaConstant.FILE_COMPLETE_RESULT_TOPIC,data.toJSONString());
	}
}
